package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishExistException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * DishService
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2023/12/5 14:12:19
 */
@Service
@RequiredArgsConstructor
public class DishServiceImpl implements DishService {

    private final DishMapper dishMapper;

    private final DishFlavorMapper dishFlavorMapper;

    private final SetmealDishMapper setmealDishMapper;

    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    @Transactional
    public void save(DishDTO dishDTO) {
        // 1. 参数校验
        Dish dishQuery = new Dish();
        dishQuery.setName(dishDTO.getName());
        Integer countByName = dishMapper.selectCount(dishQuery);
        if (countByName > 0) {
            throw new DishExistException(MessageConstant.DISH_EXIST);
        }
        // 2. 核心代码的输出
        // 2.1 菜品的数据写进数据库
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        // 默认停售
        dish.setStatus(StatusConstant.DISABLE);
        dishMapper.insert(dish);
        // 2.2 菜品的口味也要写进数据库
        saveDishFlavors(dishDTO, dish);
        // 清除缓存
        String key = getCacheKey(dish.getCategoryId());
        redisTemplate.delete(key);
    }

    @Override
    public PageResult<DishVO> page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        // 原始查询
        Dish dishQuery = new Dish();
        BeanUtils.copyProperties(dishPageQueryDTO, dishQuery);
        Page<Dish> page = dishMapper.selectPage(dishQuery);
        // 封装结果 [1, 2, 3] ---> ['1', '2', '3']  map
        List<DishVO> dishVOS = page.getResult().stream()
                .map(dish -> {
                    DishVO dishVO = new DishVO();
                    BeanUtils.copyProperties(dish, dishVO);
                    return dishVO;
                })
                .collect(Collectors.toList());
        PageResult<DishVO> pageResult = new PageResult<>();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(dishVOS);
        return pageResult;
    }

    @Override
    @Transactional
    public void removeBatch(List<String> ids) {
        // 在售状态不能删除
        Integer countByStatus = dishMapper.selectCountByIdsAndStatus(ids, StatusConstant.ENABLE);
        if (countByStatus > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        // 套餐关联不能删除？怎么确定菜被套餐关联了？
        Integer countByDishIds = setmealDishMapper.selectCountByDishIds(ids);
        if (countByDishIds > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 核心代码输出
        dishMapper.deleteByIds(ids);
        // 口味信息删除
        ids.forEach(id -> dishFlavorMapper.deleteByDishId(Long.parseLong(id)));
        // 清除缓存
        Set<String> keys = redisTemplate.keys("DISH:*");
        redisTemplate.delete(keys);
    }

    @Override
    public DishVO infoById(Long id) {
        // 给前端找（凑）数据
        // 菜品基础数据
        Dish dish = dishMapper.selectById(id);
        // 口味的列表数据
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectListByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavorList);
        return dishVO;
    }

    @Override
    @Transactional
    public void modify(DishDTO dishDTO) {
        // 1. 参数校验 - 名称和其他不能重复 - 排我
        Dish dishQuery = new Dish();
        dishQuery.setName(dishDTO.getName());
        dishQuery.setId(dishDTO.getId());
        Integer countByName = dishMapper.selectCount(dishQuery);
        if (countByName > 0) {
            throw new DishExistException(MessageConstant.DISH_EXIST);
        }
        // 2. 核心代码
        // 修改菜品
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);
        // 清空口味信息
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        // 新增口味信息
        saveDishFlavors(dishDTO, dish);
        // 清除缓存 - 基于编码
        String cacheKey = getCacheKey(dish.getCategoryId());
        redisTemplate.delete(cacheKey);

    }

    @Override
    public List<Dish> listByCategoryId(Long categoryId) {
        // 走redis取数据
        String key = getCacheKey(categoryId);
        String dishJson = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isNoneEmpty(dishJson)) {
            return JSON.parseArray(dishJson, Dish.class);
        }
        // 走数据库
        List<Dish> dishes = dishMapper.selectListByCategoryId(categoryId);
        dishes.forEach(dish -> {
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectListByDishId(dish.getId());
            dish.setFlavors(dishFlavorList);
        });
        redisTemplate.opsForValue().set(key, JSON.toJSONString(dishes));
        return dishes;
    }

    private String getCacheKey(Long categoryId) {
        return "DISH:" + categoryId;
    }

    /**
     * 保存菜肴口味
     *
     * @param dishDTO 碟形dto
     * @param dish    碟
     */
    private void saveDishFlavors(DishDTO dishDTO, Dish dish) {
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(item -> item.setDishId(dish.getId()));
            dishFlavorMapper.insertBatch(flavors);
        }
    }


    public static void main(String[] args) {
        // 字符串
        new HashMap<String, String>();
        //  哈希
        new HashMap<String, Map<String, String>>();
        //     列表（List） [5,4,1,2,3]
        new HashMap<String, List<String>>();
        // 集合（Set） -- 不可重复，无序
        new HashMap<String, Set<String>>();
        // 有序集合（ZSet）
        new HashMap<String, Set<Map<String, Integer>>>();
    }


}
